package com.tjs.netty.zk;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryNTimes;

public class ZookeeperUtil {
	
	private static CuratorFramework client;
	
	private static String zkServerPath = "localhost:2181";//多个就用逗号分隔
	private static String workSpace ;// "nettyServer"
	private static Integer retry = 3;//重试次数
	private static Integer retryTime = 5000;//每次重试间隔的时间 s
	private static Integer sessionTimeout = 60 * 1000; //session 过期时间 1分钟
	
	/**
	 * 
	* @Description:  获取Zookeeper Client
	 */
	public static CuratorFramework getZookerClient() {
		return getZookerClient(ZookeeperUtil.zkServerPath, ZookeeperUtil.workSpace, retry, retryTime, sessionTimeout);
	}
	
	/**
	 * 
	* @Description:  获取Zookeeper Client
	 */
	public static CuratorFramework getZookerClient(String workSpace) {
		return getZookerClient(ZookeeperUtil.zkServerPath, workSpace, retry, retryTime, sessionTimeout);
	}
	
	/**
	* @Description:  获取Zookeeper Client
	 */
	public static CuratorFramework getZookerClient(String zkServerPath, String workSpace, 
			Integer retry, Integer retryTime, Integer sessionTimeout
			) {
		if(client == null) {
			synchronized (ZookeeperUtil.class) {
				if(client == null) {
					RetryPolicy retryPolicy = new RetryNTimes(retry, retryTime);//重试的次数,每次重试间隔的时间
					client = CuratorFrameworkFactory
							.builder()
							.connectString(zkServerPath)
							.sessionTimeoutMs(sessionTimeout)
							.retryPolicy(retryPolicy)
							.namespace(workSpace)
							.build();
					client.start();
				}
			}
		}
		return client;
	}
	
	/**
	 * 
	 * @Description: 关闭zk客户端连接
	 */
	public static void closeZKClient() {
		if (ZookeeperUtil.client != null) {
			ZookeeperUtil.client.close();
		}
	}
	
	
	public static void main(String[] args) throws Exception {
		CuratorFramework client = ZookeeperUtil.getZookerClient();
		//client.create().creatingParentsIfNeeded().forPath("/netty/client");
		client.delete().deletingChildrenIfNeeded().forPath("/netty");
	}

}	
